<template>
  <div class="points-goods-container">
    <h2>兑换商品中心</h2>
    <div class="goods-grid">
      <el-row :gutter="20">
        <el-col :span="6" v-for="goods in goodsList" :key="goods.goodsId">
          <el-card class="goods-card" :body-style="{ padding: '0px' }">
            <img :src="goods.coverUrl" class="goods-image" />
            <div class="goods-info">
              <h3 class="goods-name">{{ goods.goodsName }}</h3>
              <p class="goods-desc">需要积分: {{ goods.pointsRequired }}</p>
              <div class="goods-footer">
                <span class="points-required">{{ goods.pointsRequired }}积分</span>
                <el-button
                    type="primary"
                    size="small"
                    @click="exchange(goods.goodsId)"
                    :disabled="goods.stock <= 0">
                  兑换
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const goodsList = ref([])
const username = localStorage.getItem('username')

onMounted(() => {
  getGoodsList()
})

const getGoodsList = async () => {
  try {
    const res = await axios.get(BASE_URL+'/api/volunteer/pointsGoods')
    goodsList.value = res.data.data
  } catch (error) {
    ElMessage.error('获取商品列表失败')
  }
}

const exchange = async (goodsId) => {
  try {
    const response = await axios.post(BASE_URL+'/api/volunteer/exchangePointsGoods', {
      username: username,
      goodsId: goodsId,
      quantity: 1
    }, {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    ElMessage.success('兑换成功')
    getGoodsList()
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '兑换失败')
    console.error('兑换错误详情:', error.response)
  }
}
</script>

<style scoped>
.points-goods-container {
  padding: 20px;
}

.goods-grid {
  margin-top: 20px;
}

.goods-card {
  margin-bottom: 20px;
  transition: all 0.3s;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.goods-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.goods-image {
  width: 100%;
  height: 180px;
  object-fit: cover;
}

.goods-info {
  padding: 15px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.goods-name {
  margin: 0 0 10px 0;
  font-size: 16px;
}

.goods-desc {
  color: #666;
  font-size: 14px;
  margin: 0 0 15px 0;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.goods-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.points-required {
  color: #f56c6c;
  font-weight: bold;
  font-size: 16px;
}
</style>